package com.web.exiaodao.business.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.MyPage;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.result.XaResult;
import com.web.webstart.base.util.XaUtil;
import com.web.exiaodao.business.entity.Address;
import com.web.exiaodao.business.repository.AddressRepository;
import com.web.exiaodao.business.service.AddressService;

@Service("AddressService")
@Transactional(readOnly = false)
public class AddressServiceImpl extends BaseService<Address> implements AddressService {

	@Autowired
	private AddressRepository addressRepository;
	
	/**
	 * 查询单条Address信息
	 * @param tId
	 * @return 返回单个Address对象
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Address> findOne(Long modelId) throws BusinessException {
		Address obj = new Address();
		if(modelId != 0){
			obj = addressRepository.findByIdAndStatusNot(modelId,XaConstant.Status.delete);
		}
		XaResult<Address> xr = new XaResult<Address>();
		if (XaUtil.isNotEmpty(obj)) {
			xr.setObject(obj);
		} else {
			throw new BusinessException(XaConstant.Message.object_not_find);
		}
		return xr;
	}

	/**
	 * 分页查询状态非status的Address数据
	 * @param status
	 * @param filterParams
	 * @param pageable
	 * @return 返回对象Address集合
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Page<Address>> findListNEStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示非删除的所有数据
			status = XaConstant.Status.delete;
		}
		filters.put("status", new SearchFilter("status", Operator.NE, status));
		Page<Address> page = addressRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), Address.class), pageable);
		XaResult<Page<Address>> xr = new XaResult<Page<Address>>();
		xr.setObject(page);
		return xr;
	}

	/**
	 * 分页查询状态status的Address数据
	 * @param status
	 * @param filterParams
	 * @param pageable
	 * @return 返回对象Address集合
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Page<Address>> findListEQStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示正常数据
			status = XaConstant.Status.valid;
		}
		filters.put("status", new SearchFilter("status", Operator.EQ, status));
		Page<Address> page = addressRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), Address.class), pageable);
		XaResult<Page<Address>> xr = new XaResult<Page<Address>>();
		xr.setObject(page);
		return xr;
	}

	/**
	 * 保存Address信息
	 * @param model
	 * @return
	 * @throws BusinessException
	 */
	@Transactional(rollbackFor = Exception.class)
	public XaResult<Address> saveOrUpdate(Address model) throws BusinessException {
		Address obj = null;
		if(XaUtil.isNotEmpty(model.getId())){
			obj = addressRepository.findOne(model.getId());
		}else{
			obj = new Address();
		}
		obj.setConsigneeName(model.getConsigneeName());
		obj.setMobile(model.getMobile());
		obj.setProvince(model.getProvince());
		obj.setCity(model.getCity());
		obj.setArea(model.getArea());
		obj.setDetailAddress(model.getDetailAddress());
		obj.setUserId(model.getUserId());
		obj.setIsDefault(model.getIsDefault());
		obj.setPostcode(model.getPostcode());
		obj = addressRepository.save(obj);
		XaResult<Address> xr = new XaResult<Address>();
		xr.setObject(obj);
		return xr;
	}

	/**
	 * 修改Address状态，可一次修改多条   3删除  -1锁定  1正常
	 * @param userId
	 * @param modelIds
	 * @param status
	 * @return 返回Address对象
	 * @throws BusinessException
	 */
	@Transactional(rollbackFor = Exception.class)
	public XaResult<Address> multiOperate(
			String modelIds,Integer status) throws BusinessException {
		XaResult<Address> xr = new XaResult<Address>();
		if(status == null){
			status = XaConstant.Status.delete;
		}
		if(modelIds != null){
			String[] ids = modelIds.split(",");
			for(String id : ids){
				Address obj = addressRepository.findByIdAndStatusNot(Long.parseLong(id),status);
				if (XaUtil.isNotEmpty(obj)) {
					obj.setStatus(status);
					obj = addressRepository.save(obj);
				} else {
					throw new BusinessException(XaConstant.Message.object_not_find);
				}
			}
		}
		return xr;
	}
	/**
	 * 
	 * 地址管理，分页查询，用户名查询
	 */
	@Override
	public XaResult<Page<Address>> findAddresskList(Integer nextPage, Integer pageSize,
			Map<String, Object> filterParams) throws BusinessException {
		//select f.id, f.province,f.city,f.area,f.consignee_name,f.detail_address,f.is_default,f.postcode,u.user_name from tb_xa_address f left join tb_xa_user u on u.id=f.user_id where f.`status`<>3
		StringBuffer sql=new StringBuffer("select f.id, f.consignee_name,f.mobile,f.province,f.city,f.area,f.detail_address,f.is_default,f.postcode,u.user_name ");
		sql.append("from tb_xa_address f left join tb_xa_user u on u.id = f.user_id ");
		sql.append(" WHERE f.STATUS<> ").append(XaConstant.Status.delete);
		//统计数据库中数据个数
		StringBuffer sql1=new StringBuffer("select count(*) ");
		sql1.append("from tb_xa_address f left join tb_xa_user u on u.id = f.user_id ");
		sql1.append(" WHERE f.STATUS<> ").append(XaConstant.Status.delete);
		//查询条件
				//收货人
				if(XaUtil.isNotEmpty(filterParams.get("LIKE_consigneeName"))){
					sql.append(" AND f.consignee_name ").append(" like '%").append(filterParams.get("LIKE_consigneeName")).append("%' ");
					sql1.append(" AND f.consignee_name ").append(" like '%").append(filterParams.get("LIKE_consigneeName")).append("%' ");
				}
				//手机号
				if(XaUtil.isNotEmpty(filterParams.get("LIKE_mobile"))){
					sql.append(" AND f.mobile ").append(" like '%").append(filterParams.get("LIKE_mobile")).append("%' ");
					sql1.append(" AND f.mobile ").append(" like '%").append(filterParams.get("LIKE_mobile")).append("%' ");
				}
				//省份
				if(XaUtil.isNotEmpty(filterParams.get("LIKE_province"))){
					sql.append(" AND f.province ").append(" like '%").append(filterParams.get("LIKE_province")).append("%' ");
					sql1.append(" AND f.province ").append(" like '%").append(filterParams.get("LIKE_province")).append("%' ");
				}
				//城市
				if(XaUtil.isNotEmpty(filterParams.get("LIKE_city"))){
					sql.append(" AND f.city ").append(" like '%").append(filterParams.get("LIKE_city")).append("%' ");
					sql1.append(" AND f.city ").append(" like '%").append(filterParams.get("LIKE_city")).append("%' ");
				}
				//区域
				if(XaUtil.isNotEmpty(filterParams.get("LIKE_area"))){
					sql.append(" AND f.area ").append(" like '%").append(filterParams.get("LIKE_area")).append("%' ");
					sql1.append(" AND f.area ").append(" like '%").append(filterParams.get("LIKE_area")).append("%' ");
				}
				//详细地址
				if(XaUtil.isNotEmpty(filterParams.get("LIKE_detailAddress"))){
					sql.append(" AND f.detail_address ").append(" like '%").append(filterParams.get("LIKE_detailAddress")).append("%' ");
					sql1.append(" AND f.detail_address ").append(" like '%").append(filterParams.get("LIKE_detailAddress")).append("%' ");
				}
				//用户名
				if(XaUtil.isNotEmpty(filterParams.get("LIKE_userName"))){
					sql.append(" AND u.user_name ").append(" like '%").append(filterParams.get("LIKE_userName")).append("%' ");
					sql1.append(" AND u.user_name ").append(" like '%").append(filterParams.get("LIKE_userName")).append("%' ");
				}
				//是否默认
				if(XaUtil.isNotEmpty(filterParams.get("EQ_isDefault"))){
					sql.append(" AND f.is_default= '").append(filterParams.get("EQ_isDefault")).append("' ");
					sql1.append(" AND f.is_default= '").append(filterParams.get("EQ_isDefault")).append("' ");
				}
				//邮编
				if(XaUtil.isNotEmpty(filterParams.get("LIKE_postcode"))){
					sql.append(" AND f.postcode ").append(" like '%").append(filterParams.get("LIKE_postcode")).append("%' ");
					sql1.append(" AND f.postcode ").append(" like '%").append(filterParams.get("LIKE_postcode")).append("%' ");
				}
				
				sql.append(" ORDER BY f.create_time DESC");
				sql1.append(" ORDER BY f.create_time DESC");
				List<Object[]> objs=this.query(sql.toString(), nextPage*pageSize, pageSize);
				List<Address> vos=new ArrayList<Address>();
				
				for (Object[] obj : objs) {	
					Address vo = new Address();
					vo.setId(Long.valueOf(obj[0].toString()));
					vo.setConsigneeName(XaUtil.isEmpty(obj[1])?"":obj[1].toString());
					vo.setMobile(XaUtil.isEmpty(obj[2])?"":obj[2].toString());
					vo.setProvince(XaUtil.isEmpty(obj[3])?"":obj[3].toString());
					vo.setCity(XaUtil.isEmpty(obj[4])?"":obj[4].toString());
					vo.setArea(XaUtil.isEmpty(obj[5])?"":obj[5].toString());
					vo.setDetailAddress(XaUtil.isEmpty(obj[6])?"":obj[6].toString());
					vo.setIsDefault((Integer) (XaUtil.isEmpty(obj[7])?"":Integer.valueOf(obj[7].toString())));
					vo.setPostcode(XaUtil.isEmpty(obj[8])?"":obj[8].toString());
					vo.setUserName(XaUtil.isEmpty(obj[9])?"":obj[9].toString());
					vos.add(vo);
				}
				//执行查询语句
				List<Object[]> obj1=this.query(sql1.toString(), null, null);
				//将得到的查询结果强转成int类型
				int count=Integer.parseInt(obj1.get(0)+"");				
				//调用分页
				Page<Address> page= new MyPage<Address>(nextPage.intValue(),pageSize.intValue(),vos,count);
				//创建结果集对象xr
				XaResult<Page<Address>> xr=new XaResult<Page<Address>>();
				//将page放入xr
				xr.setObject(page);
				return xr;
	}
	
}
